package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.ShoppingCart;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.common.ThreadLocalUtil;
import com.zrrd.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        QueryWrapper wrapper =new QueryWrapper();
        wrapper.eq("user_id", ThreadLocalUtil.getCurrentId());
        wrapper.orderByDesc("create_time");
        wrapper.ge("number",1);

        return R.success( shoppingCartService.list(wrapper));
    }
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //返回
        return R.success(shoppingCartService.addCart(shoppingCart));
    }
    @DeleteMapping("/clean")
    public R<String> clean(){
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper();
        wrapper.eq("user_id",ThreadLocalUtil.getCurrentId());
        shoppingCartService.remove(wrapper);
        return R.success("清空购物车成功");
    }
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",ThreadLocalUtil.getCurrentId());
        Long dishId = shoppingCart.getDishId();
        if (dishId != null){
            wrapper.eq("dish_id",dishId);
        }else {
            wrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }
        //查询出指定数量
        ShoppingCart cart = shoppingCartService.getOne(wrapper);
        Integer number = cart.getNumber();
        if (number>0){
            cart.setNumber(number- 1);
        }
        if (cart.getNumber()==0){
            shoppingCartService.remove(wrapper);
        }
        shoppingCartService.updateById(cart);

        //更新

        return R.success(cart);
    }

}
